package com.jx.cashier.rest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jx.cashier.rest.http.JxDccRestResponse;
import com.jx.cashier.vo.MessageType;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class RestApiMgrImpl implements RestApiMgr {
	private static final String TAG = RestApiMgrImpl.class.getSimpleName();
	private static final ObjectMapper mapper = new ObjectMapper();
	private Handler handler;

	public RestApiMgrImpl(Handler handler) {
		this.handler = handler;
	}

	@Override
	public void login(final String userNo, final String passwd) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String url = "http://" + RestApiMgr.serverAddr + ":" + RestApiMgr.serverPort;
				url += "/jxs/login?";
				url += "userNo=" + userNo;
				url += "&passwd=" + passwd;
				url += "&type=NORMAL";
				request(url, MessageType.LOGIN, null, "GET");
			}
		}).start();
	}

	private void request(String strurl, MessageType messageType, Map<String, Object> map, String method) {
		URL url = null;
		try{
			url = new URL(strurl);
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			urlConn.setRequestMethod(method);
			String json = null;
			if (map != null && !map.isEmpty()) {
				try {
					json = mapper.writeValueAsString(map);
				} catch (JsonProcessingException e) {
					handleMessage(messageType, e);
				}
			}
			if ("POST".equalsIgnoreCase(method) && json != null) {
				urlConn.setDoOutput(true);
				urlConn.setDoInput(true);
				urlConn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
				OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
				writer.write(json);
				writer.flush();
			}
			InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
			BufferedReader bufferedReader = new BufferedReader(in);
			String result = "";
			String readLine = null;
			while((readLine=bufferedReader.readLine())!=null){
				result += readLine;
			}
			in.close();
			urlConn.disconnect();
			handleMessage(messageType, result);
		}
		catch (Exception e){
			handleMessage(messageType ,e);
		}
	}

	private void handleMessage(MessageType messageType, String result) {
		Message msg = new Message();
		msg.what = messageType.ordinal();
		Bundle data = new Bundle();
		data.putString(messageType.name(), result);
		msg.setData(data);
		handler.sendMessage(msg);
	}

	private void handleMessage(MessageType messageType, Exception e) {
		Message msg = new Message();
		msg.what = messageType.ordinal();
		Bundle data = new Bundle();
		data.putString(messageType.name(), e.toString());
		msg.setData(data);
		handler.sendMessage(msg);
	}

	@Override
	public void checkVer() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String url = "http://" + RestApiMgr.serverAddr + ":" + RestApiMgr.serverPort;
				url += "/jxs/sys/ver";
				request(url, MessageType.CHECK_VERSION, null, "GET");
			}
		}).start();
	}

	@Override
	public void testNetwork(String ipAddress, String port) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String url = "http://" + RestApiMgr.serverAddr + ":" + RestApiMgr.serverPort;
				url += "/jxs/sys/ver";
				request(url, MessageType.TEST_NETWORK, null, "GET");
			}
		}).start();
	}


	@Override
	public void searchPayStatus(String outTradeNo) {
//		String url = "http://" + RestApiMgr.serverAddr + ":" + RestApiMgr.serverPort;
//		url += "/autoxfj/query_card";
//		url += outTradeNo;
//		request(url, handler);
	}


	@Override
	public void readCard(final Map<String, Object> map) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String url = "http://" + RestApiMgr.serverAddr + ":" + RestApiMgr.serverPort;
				url += "/jxs/autoxfj/query_card";
				request(url, MessageType.READ_CARD, map, "POST");
			}
		}).start();
	}

	@Override
	public void payFee(final Map<String, Object> map) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String url = "http://" + RestApiMgr.serverAddr + ":" + RestApiMgr.serverPort;
				url += "/jxs/autoxfj/do_pay_fee";
				request(url, MessageType.PAY_FEE, map, "POST");
			}
		}).start();
	}

}
